"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '07/09/2022'
    comment: 工程全局使用的变量以及函数等
"""
import os
import logging

import redis
from redis.client import Redis
from sqlalchemy import engine_from_config
from pydantic import Field
from laner.pydantic import BaseModel
from contextlib import contextmanager

from config import Config
from project.core.log import Log, LogConfig
from project.lib.aio_redis import AioRedis
from sqlalchemy.orm import sessionmaker, scoped_session

# ====================日志对象部分====================
logging.basicConfig(level=Config.LOGGER_LEVEL)  # 项目日志级别

# 普通日志
logger = Log(logger_name=str(os.getpid()), log_config=LogConfig(**Config.LOGGER), display_console=Config.DISPLAY_CONSOLE)

# 特殊日志
logger_abnormal = Log(logger_name=str(os.getpid()) + "_abnormal", log_config=LogConfig(**Config.LOGGER_ABNORMAL), display_console=Config.DISPLAY_CONSOLE)

# ====================数据库连接池部分====================
sa_engine = engine_from_config(Config.DB_OPTIONS, prefix="")
Session = scoped_session(sessionmaker(bind=sa_engine))

def get_session():
    """ 从session pool
    :return:
    """
    session = Session()
    try:
        yield session
    except Exception as ex:
        print(ex)
        session.rollback()
    finally:
        session.close()


@contextmanager
def session_maker():
    """ 从session pool
    :return:
    """
    session = Session()
    try:
        yield session
    except Exception as ex:
        session.rollback()
        raise ex
    finally:
        session.close()


# ====================redis连接部分====================
redis_pool = redis.ConnectionPool(**Config.REDIS_OPTIONS)


def get_redis() -> Redis:
    """取得redis连接
    :return:
    """
    return redis.StrictRedis(connection_pool=redis_pool)


# ====================异步redis====================
aio_redis = AioRedis()


# ====================计数器====================


class Global:

    _count = 0

    @classmethod
    def count(cls) -> int:
        """ 全局计数器
        :return:
        """
        cls._count += 1
        return cls._count


# ====================Api 接口参数====================
class ApiParam(BaseModel):
    """
    """
    path: str = Field('', title='api url路径')
    body_params: list = Field([], title='body参数')
    query_params: list = Field([], title='query参数')
    path_params: list = Field([], title='路径参数')


api_param_map: dict[str, ApiParam] = {}

